import React from "react";
import { Button, Form, Input, Modal, Select, Tooltip, Icon, Steps, Checkbox, Radio, InputNumber, Switch, Drawer, Divider, Col, Row, Cascader, message, DatePicker } from "antd";
import styles from "./robotAdd.less";
import UserSession from "@/UserSession";
import BusinessReadonly from "../ChargingManage/businessManage/businessReadonly";
import { businessTypeList, chargingAndDetail } from "@/services/chargingManage";
import { doRobotAdd } from "@/services/robotManagement";
import moment from "moment";
import { formatMessage } from 'umi-plugin-react/locale';

const { Step } = Steps;

class RobotAdd extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      businessList: [],
      caseOptions: [],
      visible: false,
      buttonLoading: false
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  initModal = () => {
    this.getBusinessList()
    this.setState({
      visible: true
    })
  }

  getBusinessList = async () => {
    const res = await businessTypeList()
    res.settlement = res.settlement.sort((a, b) => b.id - a.id)
    this.setState({ businessList: res.settlement })
  }

  changeBusiness = value => {
    this.props.form.resetFields(["planDetailId"])
    this.getCaseOptions(value)
    this.BusinessReadonly.initModal(value)
  }

  getCaseOptions = async id => {
    const res = await chargingAndDetail({ id })
    this.setState({ caseOptions: res })
  }

  changeDetailId = (value, selectedOptions) => {
    if (selectedOptions && selectedOptions[1]) {
      this.setState({ packageId: selectedOptions[1].packageId })
      this.props.form.setFieldsValue({ startDate: selectedOptions[1].startDate, endDate: selectedOptions[1].endDate })
    }
  }

  cancelModal = () => {
    const { form } = this.props;
    this.setState({
      businessList: [],
      caseOptions: [],
      visible: false,
      buttonLoading: false
    });
    form.resetFields();
  };

  checkMobile = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (!/^1[3456789]\d{9}$/.test(value)) {
      callback('请输入正确的手机号');
    }
    callback();
  }

  onSubmit = () => {
    const { infoData, applicationPlatform } = this.state;
    const { form } = this.props;
    form.validateFields((errors, values) => {
      if (!errors) {
        values.startTime = values.startTime ? moment(values.startTime).format("YYYY-MM-DD") : ''
        values.endTime = values.endTime ? moment(values.endTime).format("YYYY-MM-DD") : ''
        this.doSave(values)
      }
    });
  };

  doSave = values => {
    this.setState({ buttonLoading: true }, async () => {
      const res = await doRobotAdd(
        {
          ...values,
          applicationPlatform: "PURE_WEB",
          type: 1,
          moduleRobot: true,
          moduleKefu: false,
          platformParams: ""
        }
      )
      this.setState({ buttonLoading: false })
      if (res.code == -1) {
        return false
      }
      message.info(res.message)
      this.cancelModal()
      this.props.refreshList()
    });
  }

  disabledendTime = endValue => {
    const startValue = this.props.form.getFieldValue("startTime")

    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  render() {
    const { getFieldDecorator, getFieldValue, resetFields } = this.props.form;
    const { visible, businessList, caseOptions, buttonLoading } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    return (
      <Drawer
        visible={visible}
        onClose={this.cancelModal}
        title={formatMessage({ id: 'robotAdd.addEnterprise' })}
        width='100%'
      >
        <Form {...formItemLayout}>
         <h3>{formatMessage({ id: 'robotAdd.basicInfo' })}</h3>
          <Row>
            <Col span={12}>
             <Form.Item label={formatMessage({ id: 'robotAdd.selectBoundEnterprise' })}>
                {getFieldDecorator("enterpriseId",{rules:[{required:true,message:formatMessage({ id: 'robotAdd.pleaseSelect' })}]})(
                  <Select
                    showSearch
                    onChange={this.changeBusiness}
                    optionFilterProp="children"
                  >
                    {businessList.map(item =>
                      <Select.Option value={item.id} key={item.id}>
                        {item.name}
                      </Select.Option>
                    )}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'robotAdd.billingPlanDetails' })}>
                {getFieldDecorator("planDetailId",{rules:[{required:true,message:formatMessage({ id: 'robotAdd.pleaseSelect' })}]})(
                  <Cascader options={caseOptions} fieldNames={{ label: 'name', value: 'id', children: 'children' }} onChange={this.changeDetailId} />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'robotAdd.accountValidStartDate' })}>
                {getFieldDecorator("startTime",{rules:[{required:true,message:formatMessage({ id: 'robotAdd.pleaseSelect' })}]})(
                  <DatePicker onChange={() => resetFields(["endTime"])} />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'robotAdd.accountValidEndDate' })}>
                {getFieldDecorator("endTime",{rules:[{required:true,message:formatMessage({ id: 'robotAdd.pleaseSelect' })}]})(
                  <DatePicker disabled={!getFieldValue("startTime") } disabledDate={this.disabledendTime} />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label={formatMessage({ id: 'robotAdd.adminAccount' })}>
                {getFieldDecorator("username",{
                  rules: [{ required: true, message: formatMessage({ id: 'robotAdd.pleaseEnterAdminAccount' }) }],
                })(
                  <Input placeholder={formatMessage({ id: 'robotAdd.pleaseEnterAdminAccount' })} style={{ width: "94%" }} autoComplete="new-user" />
                )}
              </Form.Item> 
              <Form.Item label={formatMessage({ id: 'robotAdd.adminMobile' })}>
                {getFieldDecorator("mobilePhone",{
                  rules: [{ required: false, validator: this.checkMobile }],
                })(
                  <Input placeholder={formatMessage({ id: 'robotAdd.adminMobilePlaceholder' })} style={{ width: "94%" }} />
                )}
              </Form.Item> 
              <Form.Item label={formatMessage({ id: 'robotAdd.adminPassword' })}>
                {getFieldDecorator("password",{
                  rules: [{ required: true, message: formatMessage({ id: 'robotAdd.pleaseEnterAdminPassword' }) }],
                })(
                  <Input.Password placeholder={formatMessage({ id: 'robotAdd.pleaseEnterAdminPassword' })} style={{ width: "94%" }} autoComplete="new-password" />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24} style={{ textAlign: "center" }}>
              <Button onClick={this.cancelModal}>{formatMessage({ id: 'robotAdd.cancel' })}</Button>
              <Button type="primary" onClick={this.onSubmit} style={{ marginLeft: 10 }} loading={buttonLoading}>{formatMessage({ id: 'robotAdd.confirm' })}</Button>
            </Col>
          </Row>
        </Form>
        <Divider />
        <BusinessReadonly onRef={ref => this.BusinessReadonly = ref} />
      </Drawer>
    );
  }
}

export default Form.create()(RobotAdd);
